package sad.visao;


import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import javax.swing.table.AbstractTableModel;
import sad.modelo.Professor;

public class ProfessorTableModel extends AbstractTableModel {
  private List<Professor> lines;
  private String[] columns = new String[] {"Nome","Login", "Senha"};
  
  public ProfessorTableModel() {
    this.lines = new ArrayList<Professor>();
  }
  
  public Professor getProfessor(int indexLine) {
    return lines.get(indexLine);
  }
  
  public void addProfessor(Professor proto) {
    lines.add(proto);
    int lastIndex = getRowCount() - 1;
    fireTableRowsInserted(lastIndex,lastIndex);
  }
  
  public void removeProfessor(int indexLine) {
    lines.remove(indexLine);
    fireTableRowsDeleted(indexLine,indexLine);
  }
  
  public void sortByNome(){
    Collections.sort(lines, new Comparator<Professor>() {
      @Override
      public int compare(Professor o1, Professor o2) {
        return o1.getLogin().compareTo(o2.getLogin());
      }
    });
    fireTableDataChanged();
  }
  
  public void clear() {
    lines.clear();
    fireTableDataChanged();
  }
  
  public boolean isEmpty() {
    return lines.isEmpty();
  }
  
  @Override
  public int getColumnCount() {
    return columns.length;
  }
  
  @Override
  public int getRowCount() {
    return lines.size();
  }
  
  @Override
  public String getColumnName(int columnIndex) {
    return columns[columnIndex];
  }
 
  @Override
  public Class<?> getColumnClass(int columnIndex) {
    switch(columnIndex) {
      case 0:
      case 1:
      case 2:
        return String.class;
      default:
        throw new IndexOutOfBoundsException("columnIndex fora dos limites!");
    }
  }
  
  @Override
  public Object getValueAt(int rowIndex, int columnIndex) {
    Professor proto = lines.get(rowIndex);
    switch(columnIndex) {
      case 0:
        return proto.getNome();
      case 1:
        return proto.getLogin();
      case 2:
        return proto.getSenha();
      default:
        throw new IndexOutOfBoundsException("columnIndex out of bounds");
    }
  }
  
  @Override
  public void setValueAt(Object o, int linha, int coluna) {
      Professor proto = lines.get(linha);
      switch(coluna) {
        case 0:
            proto.getNome();
            break;
        case 1:
            proto.getLogin();
            break;    
        case 2:
            proto.getSenha();
            break; 
          
        default:
            throw new IndexOutOfBoundsException("columnIndex out of bounds");
      }
       fireTableCellUpdated(linha,coluna);
  }
  
  @Override
  public boolean isCellEditable(int rowIndex, int columnIndex) {
    return false;
  }
}
